package com.lib.servlet.record;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.lib.common.Constant;
import com.lib.entity.JsonResult;
import com.lib.service.RecordService;
import com.lib.service.ex.EmptyArgumentException;
import com.lib.service.ex.ServiceException;
import com.lib.service.ex.UpdateServiceException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Date;

@WebServlet(name = "RecordAgainServlet", value = "/admin/RecordAgainServlet.do")
public class RecordAgainServlet extends HttpServlet {
    private RecordService recordService = new RecordService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String rid = request.getParameter("rid");
        String backDate = request.getParameter("backDate");
        System.out.println("----------date="+backDate);
        Date date = DateUtil.parseDate(backDate);
        Date newDate = DateUtil.offsetDay(date,30);
        String nDate = DateUtil.formatDate(newDate);
        System.out.println("----------new date="+nDate);
        JsonResult jsonResult = null;
        try {
            recordService.updateRecordBackDate(rid,nDate);
            jsonResult = JsonResult.getSuccessJR();
        } catch (EmptyArgumentException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_EMPTY_ARGUMENT,e.getMessage());
        } catch (UpdateServiceException e) {
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_UPDATE,e.getMessage());
        } catch (ServiceException e) {
            e.printStackTrace();
            jsonResult = new JsonResult(Constant.JSON_STATE_SERVICE_ERROR,e.getMessage());
        }

        System.out.println("------jsonResult:"+ JSON.toJSONString(jsonResult));
        response.setCharacterEncoding("utf-8");
        response.getWriter().write(JSON.toJSONString(jsonResult));
        response.getWriter().flush();
        response.getWriter().close();
    }
}
